import React from "react";
import {findNodeHandle, Image, TextInput, TouchableOpacity, UIManager, View, StyleSheet} from "react-native";
import EButton from "../utils/EButton";
import {FileInfo} from "../../libs/sdk/echatim/core/fileclient/FileServerClient";
import UploadFileComponent from "../uploader/UploadFileComponent";
import {faces as facesResource} from "./faces";
import Beans from "../../libs/sdk/echatim/common/utils";
import EHr from "../utils/EHr";
import Toast from "../toast/Toast";
import {Resource} from "../../resource/Resource";


type MessageInputComponentProp = {
    onFileUploaded:(fileInfo:FileInfo)=>void
    onFileStartUpload:(fileInfo:FileInfo)=>void
    onSendMessage:(msgType:string, jsonBody:any)=>void
    onAdjustLayout:(height:number)=>void
}

type MessageInputComponentState = {
    height:number,
    msgContentText:string,
    faceDisplay:'flex'|'none'
}


export default class MessageInputComponent extends React.Component<MessageInputComponentProp, MessageInputComponentState> {
    private messageInput:TextInput|any;
    private faceRef:View|any;

    constructor(props:MessageInputComponentProp) {
        super(props);

        this.state = {
            msgContentText:'',
            height:56,
            faceDisplay:'none'
        };
    }

    public clearInput(){
        this.setState({
            msgContentText:''
        });
        this.messageInput.clear();
    }

    onChangeMessage(text:string){
        this.setState({
            msgContentText:text
        })
    }

    onSendMessage(jsonBody:any){
        if(!this.state.msgContentText){
            Toast.show('请输入发送内容');
            return;
        }
        if(this.state.faceDisplay === 'flex'){
            this.showOrHideFacesSelector(); // 自动隐藏表情框
        }
        this.props.onSendMessage('TEXT', jsonBody);
    }

    onFileUploaded(fileInfo:FileInfo){
        this.props.onSendMessage(fileInfo.type ? fileInfo.type : 'FILE', {
            body:fileInfo.url,
            name:fileInfo.originFileName,
            size:fileInfo.size
        });
    }
    onFileStartUpload(fileInfo:FileInfo){
        this.props.onFileStartUpload(fileInfo);
    }

    getTextInputRef = (textInput) => {
        this.messageInput = textInput;
        return textInput;
    };


    measureFaceComponentSize():Promise<any>{
        const handle = findNodeHandle(this.faceRef);
        return new Promise((resolve) => {
            UIManager.measure(handle as any, (x, y, width, height, pageX, pageY) => {
                resolve({
                    x,
                    y,
                    width,
                    height,
                    pageX,
                    pageY
                });
            });
        });
    }


    showOrHideFacesSelector(){
        const self = this;
        const prevState = this.state;
        const faceDisplay = this.state.faceDisplay === 'flex' ? 'none' : 'flex';

        this.setState({
            msgContentText:prevState.msgContentText,
            height:prevState.height,
            faceDisplay:faceDisplay,
        },()=>{
            // FIXME: 在回调里, 组件的尺寸也没变化, 需要加延时操作
            setTimeout(function () {
                self.measureFaceComponentSize().then((resp)=>{
                    console.log(`measureSize:${Beans.json(resp)}`);
                    self.setState({
                        msgContentText:self.state.msgContentText,
                        height:self.state.faceDisplay === 'flex' ? 56 + resp.height : 56,// 使用最新的状态来判断
                        faceDisplay:self.state.faceDisplay,
                    },()=>{
                        self.props.onAdjustLayout(self.state.faceDisplay === 'flex' ? 56 + resp.height : 56);
                    })
                })
            }, 1);
        });
    }

    appendFace(faceName){
        console.log(`appendFace:${faceName}`);
        this.setState({
            msgContentText:this.state.msgContentText + faceName
        })
    }

    componentDidUpdate(prevProps: Readonly<MessageInputComponentProp>, prevState: Readonly<MessageInputComponentState>, snapshot?: any): void {
        const self = this;
        self.measureFaceComponentSize().then((resp)=>{
            console.log(`componentDidUpdate: measureSize:${Beans.json(resp)}`);
        })
    }

    getFaceRef = (faceRef) => {
        this.faceRef = faceRef;
        return faceRef;
    };

    render() {
        return (
            <View style={messageInputStyles.container}>
                <View style = {[messageInputStyles.actionBtnContainer]}>
                    <TextInput ref={this.getTextInputRef} style={messageInputStyles.textInput}
                               value={this.state.msgContentText}
                               onChangeText={(text)=>this.onChangeMessage(text)}
                               onSubmitEditing={(e)=>this.onChangeMessage(this.state.msgContentText)}  />
                    <TouchableOpacity activeOpacity={1} onPress={() => this.showOrHideFacesSelector()}>
                        <Image style={messageInputStyles.faceBtn}  source={Resource.face} />
                    </TouchableOpacity>
                    <UploadFileComponent component={<Image style={messageInputStyles.upload}
                                                           source={Resource.open} />}
                                         onStartUpload={(info)=>this.onFileStartUpload(info)}
                                         onUploaded={(info)=>this.onFileUploaded(info)} />
                    <EButton title={'发送'} onPress={()=>{this.onSendMessage({body:this.state.msgContentText})}} />
                </View>
                <EHr height={8} style={{display:this.state.faceDisplay}} />
                <View ref={this.getFaceRef} style={[messageInputStyles.faceContainer, {display:this.state.faceDisplay}]}>
                    {facesResource.map((item)=>{
                        return <TouchableOpacity key={`touch-${item.name}`} activeOpacity={1} onPress={() => this.appendFace(item.name)}>
                                 <Image key={item.name} style={messageInputStyles.face}
                                          source={item.resource} />
                               </TouchableOpacity>
                    })}
                </View>
            </View>
        )

    }
}



const messageInputStyles = StyleSheet.create({
    container: {
        backgroundColor:'#fff',
        padding:8,
        justifyContent:'space-between'
    },
    actionBtnContainer:{
        height:40,
        flexDirection: 'row',
        alignItems:'center'
    },
    textInput:{
        borderWidth:0.5,
        borderRadius:4,
        flex:1,
        height:36
    },
    upload:{
        width: 24,
        height: 24
    },
    faceBtn:{
        width: 24,
        height: 24,
        marginLeft:4,
        marginRight:4
    },
    faceContainer:{
        flexDirection:'row',
        flexWrap:'wrap',
        alignItems:'flex-end',
        borderWidth:0.01,
    },
    face:{
        width: 24,
        height: 24,
        marginTop:2,
        marginBottom:2,
        marginLeft:4,
        marginRight: 4
    }
});
